package com.alibaba.task;

import com.alibaba.mapper.ArticleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Set;

/**
 *
 * @author ZhouYaDong
 * @date 2025/9/25
 * @description
 */
@Slf4j
@Service
public class ArticleViewTask {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private ArticleMapper articleMapper;

    private static final String ARTICLE_VIEW_KEY_PREFIX = "article:view:";

    /**
     * 每隔两分钟同步一次文章浏览量到数据库
     */

    @Scheduled(fixedRate = 1000 * 60 * 2)
    public void syncViewCountToDB() {
        long start = System.currentTimeMillis();
        Set<String> keys = redisTemplate.keys(ARTICLE_VIEW_KEY_PREFIX + "*");

        if (keys.isEmpty()) {
            log.info("[ViewCountSync] No data to sync at {}", LocalDateTime.now());
            return;
        }

        log.info("[ViewCountSync] Start syncing {} records at {}", keys.size(), LocalDateTime.now());

        for (String key : keys) {
            Object val = redisTemplate.opsForValue().get(key);
            if (val == null) {
                log.warn("[ViewCountSync] Key {} has no value, skip.", key);
                continue;
            }
            Integer count = Integer.valueOf(val.toString());
            Long articleId = Long.valueOf(key.substring(ARTICLE_VIEW_KEY_PREFIX.length()));
            // 同步到数据库
            articleMapper.increaseViewCount(articleId,  count);
            redisTemplate.delete(key);
            log.debug("[ViewCountSync] ArticleId={} incremented by {} and key deleted.", articleId, count);
        }

        log.info("[ViewCountSync] Completed. Total keys: {}, Time used: {} ms",
                keys.size(), System.currentTimeMillis() - start);
    }
}
